package com.taptech.doufu.util;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager.BadTokenException;
import android.view.inputmethod.InputMethodManager;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.taptech.doufu.R;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.constant.Constant;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Timer;
import java.util.TimerTask;

public class UIUtil {

	private static final String TAG = "SDK_Sample.Util";

	private static Toast mToast;

	// 两次点击按钮之间的点击间隔不能少于1000毫秒
	private static final int MIN_CLICK_DELAY_TIME = 500;
	private static long lastClickTime;

	public static boolean isFastClick() {
		boolean flag = false;
		long curClickTime = System.currentTimeMillis();
		if ((curClickTime - lastClickTime) <= MIN_CLICK_DELAY_TIME) {
			flag = true;
		}
		lastClickTime = curClickTime;
		return flag;
	}



	/**
	 * Convert char to byte
	 *
	 * @param c
	 *            char
	 * @return byte
	 */
	private static byte charToByte(char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}

	/*
	 * 16进制数字字符�?
	 */
	private static String hexString = "0123456789ABCDEF";

	/*
	 * 将字符串编码�?6进制数字,适用于所有字符（包括中文�?
	 */
	public static String toHexString(String str) {
		// 根据默认编码获取字节数组
		byte[] bytes = str.getBytes();
		StringBuilder sb = new StringBuilder(bytes.length * 2);
		// 将字节数组中每个字节拆解�?�?6进制整数
		for (int i = 0; i < bytes.length; i++) {
			sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
			sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
		}
		return sb.toString();
	}

	// 转换十六进制编码为字符串
	public static String hexToString(String s) {
		if ("0x".equals(s.substring(0, 2))) {
			s = s.substring(2);
		}
		byte[] baKeyword = new byte[s.length() / 2];
		for (int i = 0; i < baKeyword.length; i++) {
			try {
				baKeyword[i] = (byte) (0xff & Integer.parseInt(
						s.substring(i * 2, i * 2 + 2), 16));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		try {
			s = new String(baKeyword, "utf-8");// UTF-16le:Not
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return s;
	}

	public static byte[] bmpToByteArray(final Bitmap bmp,
			final boolean needRecycle) {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		bmp.compress(CompressFormat.PNG, 100, output);
		if (needRecycle) {
			bmp.recycle();
		}

		byte[] result = output.toByteArray();
		try {
			output.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	public static byte[] getHtmlByteArray(final String url) {
		URL htmlUrl = null;
		InputStream inStream = null;
		try {
			htmlUrl = new URL(url);
			URLConnection connection = htmlUrl.openConnection();
			HttpURLConnection httpConnection = (HttpURLConnection) connection;
			int responseCode = httpConnection.getResponseCode();
			if (responseCode == HttpURLConnection.HTTP_OK) {
				inStream = httpConnection.getInputStream();
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] data = inputStreamToByte(inStream);

		return data;
	}

	public static byte[] inputStreamToByte(InputStream is) {
		try {
			ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
			int ch;
			while ((ch = is.read()) != -1) {
				bytestream.write(ch);
			}
			byte imgdata[] = bytestream.toByteArray();
			bytestream.close();
			return imgdata;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	public static byte[] readFromFile(String fileName, int offset, int len) {
		if (fileName == null) {
			return null;
		}

		File file = new File(fileName);
		if (!file.exists()) {
			Log.i(TAG, "readFromFile: file not found");
			return null;
		}

		if (len == -1) {
			len = (int) file.length();
		}

		Log.d(TAG, "readFromFile : offset = " + offset + " len = " + len
				+ " offset + len = " + (offset + len));

		if (offset < 0) {
			Log.e(TAG, "readFromFile invalid offset:" + offset);
			return null;
		}
		if (len <= 0) {
			Log.e(TAG, "readFromFile invalid len:" + len);
			return null;
		}
		if (offset + len > (int) file.length()) {
			Log.e(TAG, "readFromFile invalid file len:" + file.length());
			return null;
		}

		byte[] b = null;
		try {
			RandomAccessFile in = new RandomAccessFile(fileName, "r");
			b = new byte[len];
			in.seek(offset);
			in.readFully(b);
			in.close();

		} catch (Exception e) {
			Log.e(TAG, "readFromFile : errMsg = " + e.getMessage());
			e.printStackTrace();
		}
		return b;
	}

	public static int computeSampleSize(BitmapFactory.Options options,

	int minSideLength, int maxNumOfPixels) {

		int initialSize = computeInitialSampleSize(options, minSideLength,

		maxNumOfPixels);

		int roundedSize;

		if (initialSize <= 8) {

			roundedSize = 1;

			while (roundedSize < initialSize) {

				roundedSize <<= 1;

			}

		} else {

			roundedSize = (initialSize + 7) / 8 * 8;

		}

		return roundedSize;
	}

	private static int computeInitialSampleSize(BitmapFactory.Options options,

	int minSideLength, int maxNumOfPixels) {

		double w = options.outWidth;

		double h = options.outHeight;

		int lowerBound = (maxNumOfPixels == -1) ? 1 :

		(int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));

		int upperBound = (minSideLength == -1) ? 128 :

		(int) Math.min(Math.floor(w / minSideLength),

		Math.floor(h / minSideLength));

		if (upperBound < lowerBound) {

			// return the larger one when there is no overlapping zone.

			return lowerBound;

		}

		if ((maxNumOfPixels == -1) &&

		(minSideLength == -1)) {

			return 1;

		} else if (minSideLength == -1) {

			return lowerBound;

		} else {

			return upperBound;

		}
	}

	/**
	 * 以最省内存的方式读取图片
	 */
	public static Bitmap readBitmap(final String path) {
		try {
			FileInputStream stream = new FileInputStream(new File(path
					+ "test.jpg"));
			BitmapFactory.Options opts = new BitmapFactory.Options();
			opts.inSampleSize = 8;
			opts.inPurgeable = true;
			opts.inInputShareable = true;
			Bitmap bitmap = BitmapFactory.decodeStream(stream, null, opts);
			return bitmap;
		} catch (Exception e) {
			return null;
		}
	}

	private static final int MAX_DECODE_PICTURE_SIZE = 1920 * 1440;

	public static final void showResultDialog(Context context, String msg,
			String title) {
		if (msg == null)
			return;
		String rmsg = msg.replace(",", "\n");
		Log.d("Util", rmsg);
		new AlertDialog.Builder(context).setTitle(title).setMessage(rmsg)
				.setNegativeButton("确定", null).create().show();

	}

	public static final void showEnsureDialog(Activity context, String title,
			final EnsureListener listener) {

		AlertDialog dialog;
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle(title);
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				listener.sure();
				dialog.dismiss();
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				listener.cancel();
				dialog.dismiss();
			}
		});
		dialog = builder.create();
		dialog.show();
	}

	private static PopupWindow window;

	public static final void showProgressDialog(Activity activity) {
		try {
			dismissDialog();
			if (window == null) {
				window = new PopupWindow();
				window.setWidth(LayoutParams.WRAP_CONTENT);
				window.setHeight(LayoutParams.WRAP_CONTENT);
				window.setBackgroundDrawable(new ColorDrawable());
				window.setOutsideTouchable(false);
				View baseView = activity.getLayoutInflater().inflate(
						R.layout.listview_footer, null);
				window.setContentView(baseView);
			}
			if (!activity.isFinishing()) {
				try {
					window.showAtLocation(activity.getWindow().getDecorView(),
							Gravity.CENTER, 0, 0);
				}catch(BadTokenException e){

				}catch (Exception e) {
					UIUtil.toastMessage(activity,Constant.loadingFail);
				}

			}
		} catch (NullPointerException e) {
			e.printStackTrace();
		}
	}

	public static void showLoadingDialog(Activity activity,String tip) {
		dismissDialog();
		if (window == null) {
			window = new PopupWindow();
			window.setWidth(LayoutParams.WRAP_CONTENT);
			window.setHeight(LayoutParams.WRAP_CONTENT);
			window.setBackgroundDrawable(new ColorDrawable());
			window.setOutsideTouchable(false);
			View baseView = activity.getLayoutInflater().inflate(
					R.layout.listview_footer, null);
			window.setContentView(baseView);
		}
		if (!activity.isFinishing()) {
			try {
				window.showAtLocation(activity.getWindow().getDecorView(),
						Gravity.CENTER, 0, 0);
			}catch(BadTokenException e){
			}catch (Exception e) {
				UIUtil.toastMessage(activity,Constant.loadingFail);
			}

		}
	}


	public static final void dismissDialog() {
		try {
			if (window != null && window.isShowing()) {
				window.dismiss();
			}
		} catch (IllegalArgumentException e) {
			// TODO: handle exception
			e.printStackTrace();
		} catch (IllegalStateException e){}

	}

	/**
	 * 打印消息并且用Toast显示消息
	 *
	 * @param activity
	 * @param message
	 * @param logLevel
	 *            填d, w, e分别代表debug, warn, error; 默认是debug
	 *
	 *            部分手机显示不了，暂时停用，使用系统提供的Toast
	 */
	public static final void toastMessage(Context activity,
			final String message, String logLevel) {
		if ("w".equals(logLevel)) {
			Log.w("sdkDemo", ""+message);
		} else if ("e".equals(logLevel)) {
			Log.e("sdkDemo", ""+message);
		} else {
			Log.d("sdkDemo", ""+message);
		}
		// activity.runOnUiThread(new Runnable() {
		// @Override
		// public void run() {
		// // TODO Auto-generated method stub
		if (mToast != null) {
			mToast.cancel();
			mToast = null;
		}
		if(activity==null)
			activity = WeMediaApplication.applicationContext;
		mToast = Toast.makeText(activity, message, Toast.LENGTH_SHORT);
		mToast.setGravity(Gravity.CENTER, 0, 0);
		mToast.show();
		// }
		// });
	}

	/**
	 * 打印消息并且用Toast显示消息
	 *
	 * @param activity
	 * @param message
	 *            填d, w, e分别代表debug, warn, error; 默认是debug
	 */
	public static final void toastMessage(final Context activity,
			final String message) {
		Toast.makeText(activity,message,Toast.LENGTH_LONG).show();
//		toastMessage(activity, message, null);
	}

	/**
	 * 根据�?��网络连接(String)获取bitmap图像
	 *
	 * @param imageUri
	 * @return
	 * @throws MalformedURLException
	 */
	public static Bitmap getbitmap(String imageUri) {
		Log.v(TAG, "getbitmap:" + imageUri);
		// 显示网络上的图片
		Bitmap bitmap = null;
		try {
			URL myFileUrl = new URL(imageUri);
			HttpURLConnection conn = (HttpURLConnection) myFileUrl
					.openConnection();
			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(is);
			is.close();

			Log.v(TAG, "image download finished." + imageUri);
		} catch (IOException e) {
			e.printStackTrace();
			Log.v(TAG, "getbitmap bmp fail---");
			return null;
		}
		return bitmap;
	}

	public static void setListViewHeightBasedOnChildren(ListView listView) {
		// 获取ListView对应的Adapter
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			// pre-condition
			return;
		}

		int totalHeight = 0;
		for (int i = 0, len = listAdapter.getCount(); i < len; i++) { // listAdapter.getCount()返回数据项的数目
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0); // 计算子项View 的宽高
			totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		// listView.getDividerHeight()获取子项间分隔符占用的高度
		// params.height最后得到整个ListView完整显示需要的高度
		listView.setLayoutParams(params);
	}

	public interface EnsureListener {
		void sure();

		void cancel();
	}

	public static void showStarLevel(int star, TextView textView){
		String starLevel = "";
		switch (star) {
		case 1:
			starLevel = Constant.starLevel_01;
			textView.setBackgroundResource(R.drawable.sweep_star_level_gray);
			break;
		case 2:
			starLevel = Constant.starLevel_02;
			textView.setBackgroundResource(R.drawable.sweep_star_level_gray);
			break;
		case 3:
			starLevel = Constant.starLevel_03;
			textView.setBackgroundResource(R.drawable.sweep_star_level_gray);
			break;
		case 4:
			starLevel = Constant.starLevel_04;
			textView.setBackgroundResource(R.drawable.sweep_star_level_green);
			break;
		case 5:
			starLevel = Constant.starLevel_05;
			textView.setBackgroundResource(R.drawable.sweep_star_level_green);
			break;
		default:
			break;
		}
		textView.setText(starLevel);
	}
	public static String showStarLevel(String star , TextView textView){
		if(star == null){
			return null;
		}
		int startCount =0;
		if(star.contains(".")){
			startCount = Integer.valueOf(star.substring(0, star.indexOf(".")));
		}
		else{
			startCount = Integer.valueOf(star);
		}
		String starLevel = "";
		switch (startCount) {
		case 1:
			starLevel = Constant.starLevel_01;
			textView.setBackgroundResource(R.drawable.sweep_star_level_gray);
			break;
		case 2:
			starLevel = Constant.starLevel_02;
			textView.setBackgroundResource(R.drawable.sweep_star_level_gray);
			break;
		case 3:
			starLevel = Constant.starLevel_03;
			textView.setBackgroundResource(R.drawable.sweep_star_level_gray);
			break;
		case 4:
			starLevel = Constant.starLevel_04;
			textView.setBackgroundResource(R.drawable.sweep_star_level_green);
			break;
		case 5:
			starLevel = Constant.starLevel_05;
			textView.setBackgroundResource(R.drawable.sweep_star_level_green);
			break;
		default:
			break;
		}
		return starLevel;
	}
	public static String showStarLevel(int star){
		String starLevel = "";
		switch (star) {
		case 1:
			starLevel = Constant.starLevel_01;
			break;
		case 2:
			starLevel = Constant.starLevel_02;
			break;
		case 3:
			starLevel = Constant.starLevel_03;
			break;
		case 4:
			starLevel = Constant.starLevel_04;
			break;
		case 5:
			starLevel = Constant.starLevel_05;
			break;
		default:
			break;
		}
		return starLevel;
	}




	// 隐藏软键盘
	public static void hideCurrentSoftInput(Activity activity) {
		if (activity != null) {
			InputMethodManager inputMethodManager = (InputMethodManager) activity
					.getSystemService(Context.INPUT_METHOD_SERVICE);
			if (inputMethodManager.isActive()) {
				if (null != activity.getCurrentFocus()
						&& activity.getCurrentFocus().getWindowToken() != null) {
					inputMethodManager.hideSoftInputFromWindow(activity
									.getCurrentFocus().getWindowToken(),
							InputMethodManager.HIDE_NOT_ALWAYS);
				}
			}
		}
	}

	public static void showMyToast(final Toast toast, final long cnt) {
		final Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				toast.show();
			}
		}, 0, 3000);
		new Timer().schedule(new TimerTask() {
			@Override
			public void run() {
				toast.cancel();
				timer.cancel();
			}
		}, cnt );
	}

	private static Toast toast;

	public static void showToast(Context context,
								 String content) {
		if (toast == null) {
			toast = Toast.makeText(context,
					content,
					Toast.LENGTH_SHORT);
		} else {
			toast.setText(content);
		}
		toast.show();
	}


	/**
	 * 判断当前view是否在屏幕可见
	 */
	public static boolean getLocalVisibleRect(Context context, View view, int offsetY) {
		Point p = new Point();
		((Activity) context).getWindowManager().getDefaultDisplay().getSize(p);
		int screenWidth = p.x;
		int screenHeight = p.y;
		Rect rect = new Rect(0, 0, screenWidth, screenHeight);
		int[] location = new int[2];
		location[1] = location[1] + ScreenUtil.dip2px(context, offsetY);
		view.getLocationInWindow(location);
		view.setTag(location[1]);//存储y方向的位置
		if (view.getLocalVisibleRect(rect)) {
			return true;
		} else {
			return false;
		}
	}
}
